package org.cll.lagou.study.minicat.server;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 描述信息:
 * 封装Response对象，需要提供输出方法
 * @author CLL
 * @version 1.0
 * @date 2020/7/2 20:54
 */
@NoArgsConstructor
public class IResponse {

    @Getter
    @Setter
    private OutputStream outputStream;

    public IResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 根据请求路径，输出静态资源
     * @param url   请求路径
     */
    public void outputHtml(String url) throws IOException {
        String absoluteResourcePath = IStaticResourceUtil.getFileAbsolutePath(url);

        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            // 返回静态资源
            IStaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 返回404页面
            outputResponseStream(IHttpProtocolUtil.getHttpResponse404());
        }
    }

    public void outputResponseStream(String responseText) throws IOException {
        outputStream.write(responseText.getBytes());
        outputStream.close();
    }

}